/*
 * @(#)AttributedFigure.java  3.1  2006-06-17
 *
 * Copyright (c) 1996-2006 by the original authors of JHotDraw
 * and all its contributors ("JHotDraw.org")
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * JHotDraw.org ("Confidential Information"). You shall not disclose
 * such Confidential Information and shall use it only in accordance
 * with the terms of the license agreement you entered into with
 * JHotDraw.org.
 */

package umage.figures;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.ImageObserver;
import java.io.IOException;

import javax.swing.ImageIcon;

import org.jhotdraw.draw.RectangleFigure;
import org.jhotdraw.xml.DOMInput;
import org.jhotdraw.xml.DOMOutput;

import umage.core.ImageUtil;

public class ImageFigure extends RectangleFigure implements ImageObserver {
	protected String imageName;
	protected String imageLoc;
	private ImageIcon image;
	
    /** Creates a new instance. */
    public ImageFigure() {
        super();
    }
    
    public ImageFigure(String imageName, String imageLoc) {
    	setImage(imageName, imageLoc);
    }
	
    public void setImage(String imageName, String imageLoc) {
    	this.imageName = imageName;
    	this.imageLoc = imageLoc;
    	image = ImageUtil.getImageIcon(this.imageName, this.imageLoc);
    	if (image == null) return;
    	Point2D.Double start = new Point2D.Double(0, 0);
    	Point2D.Double end = new Point2D.Double(image.getIconWidth(), image.getIconHeight());
    	basicSetBounds(start, end);
    }
    
    public ImageIcon getImage() {
    	return image;
    }
    
    @Override
    public void drawFigure(Graphics2D g) {
    	Rectangle2D.Double bounds = getBounds();
		if (image != null) {
			g.drawImage(image.getImage(), (int)bounds.x, (int)bounds.y, (int)bounds.width, (int)bounds.height, this);
		} else {
			g.setColor(Color.gray);
			g.fillRect((int)bounds.x, (int)bounds.y, (int)bounds.width, (int)bounds.height);
		}
    }
    
	@Override
	public boolean imageUpdate(Image img, int infoflags, int x, int y,
			int width, int height) {
		if ((infoflags & (FRAMEBITS | ALLBITS)) != 0) {
			invalidate();
		}
		return (infoflags & (ALLBITS | ABORT)) == 0;
	}
    
	@Override
	public void read(DOMInput in) throws IOException {
		super.read(in);
		String imageName = in.getAttribute("imageName", "");
		String imageLoc = in.getAttribute("imageLoc", "");
		setImage(imageName, imageLoc);
	}
	
	@Override
	public void write(DOMOutput out) throws IOException {
		super.write(out);
		out.addAttribute("imageName", imageName);
		out.addAttribute("imageLoc", imageLoc);
	}
	
    public ImageFigure clone() {
        ImageFigure that = (ImageFigure) super.clone();
        that.setImage(imageName, imageLoc);
        return that;
    }
	
}
